package scope

import "gorm.io/gorm"

func WithOrder(column string, asc bool) IScope {
	return Order{
		Column: column,
		Asc:    asc,
	}
}

func WithCreateAt(desc ...bool) IScope {
	return Order{
		Column: "created_at",
		Asc:    len(desc) == 0 || !desc[0],
	}
}

func WithOrderSet(set map[string]bool) IScope {
	var orders Orders
	for column, asc := range set {
		orders = append(orders, Order{
			Column: column,
			Asc:    asc,
		})
	}
	return orders
}

type Orders []Order

func (o Orders) MakeScope() Scope {
	return func(db *gorm.DB) *gorm.DB {
		for _, order := range o {
			if order.Column == "" {
				continue
			}

			if order.Asc {
				db = db.Order(order.Column)
			} else {
				db = db.Order(order.Column + " DESC")
			}
		}
		return db
	}
}

type Order struct {
	Column string
	Asc    bool
}

func (o Order) MakeScope() Scope {
	return func(db *gorm.DB) *gorm.DB {
		if o.Column == "" {
			return db
		}
		if o.Asc {
			return db.Order(o.Column)
		}
		return db.Order(o.Column + " DESC")
	}
}
